import React from "react";
import Admin from "../../layout/Admin";
import CarouselModel from "../../model/carousel";
import {formLayout, formTailLayout, getBase64, log} from "../quotation/quotation";
import {Button, Form, Input, Modal, Radio, Upload, Carousel as AntdCarousel, Popover} from "antd";
import {MinusCircleOutlined, PlusOutlined, UploadOutlined} from "@ant-design/icons";
import Info from "../../service/info";

class Carousel extends React.Component {

    constructor(props) {
        super(props)
        this.model = new CarouselModel()
        this.state = {
            list: [],
            previewImage: null,
            images: [],
            style: 1,
            modal: {
                preview: false,
            }
        }
    }

    componentDidMount() {
        this.get()
    }

    get = () => {
        this.model
            .get()
            .then((res) => {
                const data = res.data
                if (data.code === 0) {
                    this.setState({
                        list: data.data,
                    })
                }
            })
    }

    callModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: false
            }
        })
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: () => false,

            onChange: ({fileList,}) => {
                this.setState({
                    [name]: fileList,
                })
            },

            onPreview: async (file) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj);
                }

                this.setState({
                    previewImage: file.url || file.preview,
                    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                }, () => this.callModal('preview'));
            },

            fileList,
        }

    }


    renderImgsFields = (fields, {add, remove,}, lineupKey) => {
        return (
            <>
                {fields.map(({ key, name, fieldKey, ...restField }, index) => (
                    <div key={key} style={{position: 'relative',}}>
                        <Form.Item
                            {...restField}
                            name={[name, 'Url']}
                            fieldKey={[fieldKey, 'Url']}
                            label={`跳转路由${index + 1}`}
                        >
                            <Input placeholder='跳转路由'/>
                        </Form.Item>
                        <div
                            style={{
                                position: 'absolute',
                                right: '10px',
                                top: '50%',
                                transform: 'translateY(-50%)',
                            }}
                        >
                            <MinusCircleOutlined onClick={() => remove(name)} style={{margin: '10px'}} />
                        </div>
                    </div>
                ))}
                <Form.Item {...formTailLayout}>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        添加轮播图子项
                    </Button>
                </Form.Item>
            </>
        )
    }

    onAdd = (values) => {
        let fm = new FormData()
        fm.append('Style', this.state.style)

        if (values.Imgs) {
            if (this.state.images.length !== values.Imgs.length) {
                Info.warning('路由地址需要和上传图片数量一致， 且一一对应')
            } else {
                const imgs = this.state.images.map((img, index) => ({
                    Image: img.name,
                    Url: values.Imgs[index].Url,
                }))
                fm.append('Imgs', JSON.stringify(imgs))
                this.state.images.map((img => fm.append(img.name, img.originFileObj)))
                this.model
                    .add(fm)
                    .then(res => {
                        const data = res.data
                        if (data.code === 0) {
                            Info.success('添加首页轮播图成功')
                            this.setState({
                                images: [],
                            })
                            this.addForm && this.addForm.resetFields()
                            this.get()
                        }
                    })
            }
        } else {
            Info.warning('路由地址需要和上传图片数量一致， 且一一对应')
        }
    }


    onRadioChange = (event) => {
        this.setState({
            style: event.target.value,
        })
    }

    show = () => {
        this.callModal('show')
    }

    render() {

        const list = this.state.list
        const curImages = list.find(imgs => imgs.Style === this.state.style)

        log(curImages)

        return (
            <>
                <Modal
                    visible={this.state.modal.show}
                    onCancel={() => this.cancelModal('show')}
                    width={'80%'}
                >
                    {/*<AntdCarousel*/}
                    {/*    arrows*/}
                    {/*    nextArrow={<div>*/}
                    {/*        <span>next</span>*/}
                    {/*    </div>}*/}
                    {/*>*/}
                    {/*    {curImages && curImages.Imgs.map((img, index) => {*/}
                    {/*        return <div key={index} style={{background: 'black',}}>*/}
                    {/*            <img src={img.Image} alt='' style={{background: 'black', margin: '0 auto',}}/>*/}
                    {/*        </div>*/}
                    {/*    })}*/}
                    {/*</AntdCarousel>*/}
                    <div style={{display: 'flex', flexWrap: 'wrap',}}>
                        {curImages && curImages.Imgs.map((img, index) => {
                            return <div style={{width: '25%',}} key={index}>
                                <img src={img.Image} alt='' style={{width: '100%',}}/>
                                <Popover
                                    content={img.Url}
                                >
                                    <a>查看路由</a>
                                </Popover>
                                <a
                                    style={{marginLeft: '8px',}}
                                    onClick={() => {
                                        this.setState({
                                            previewImage: img.Image,
                                        }, () => this.callModal('preview'))
                                    }}
                                >查看大图</a>
                            </div>
                        })}
                    </div>

                </Modal>
                <Admin>
                    <div className='list-container'>
                        <Modal
                            visible={this.state.modal.preview}
                            // title={this.state.previewTitle}
                            footer={null}
                            onCancel={() => this.cancelModal('preview')}
                            width={'80%'}
                        >
                            <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                        </Modal>
                        <Form
                            {...formLayout}
                            name='add'
                            ref={el => this.addForm = el}
                            onFinish={this.onAdd}
                        >
                            <Form.Item
                                label='轮播图种类'
                            >
                                <Radio.Group value={this.state.style} onChange={this.onRadioChange} >
                                    <Radio value={1}>顶部轮播图</Radio>
                                    <Radio value={2}>中部轮播图</Radio>
                                    <Radio value={3}>找出茶轮播图</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                label='现存轮播图'

                            >
                                {curImages
                                    ? <a onClick={this.show}>查看</a>
                                    : <span>尚未上传</span>
                                }
                            </Form.Item>

                            <Form.Item
                                label='图片'
                            >
                                <Upload
                                    listType="picture-card"
                                    fileList={this.state.images}
                                    {...this.uploadInputProps('images')}
                                    multiple={true}
                                >
                                    <Button icon={<UploadOutlined />}>添加轮播图图片</Button>
                                </Upload>
                            </Form.Item>

                            <Form.List name='Imgs'>
                                {(fields, { add, remove, },) => this.renderImgsFields(fields, { add, remove, }, 'Imgs')}
                            </Form.List>

                            <Form.Item
                                label='注意事项'
                            >
                                <span>
                                    路由地址需要和上传图片数量一致， 且一一对应。 需要修改请直接重新上传。
                                </span>
                            </Form.Item>
                            <Form.Item {...formTailLayout}>

                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>

                            </Form.Item>
                        </Form>
                    </div>
                </Admin>
            </>
        )
    }

}

export default Carousel